'use strict';
const path = require('path');
const fse = require('fs-extra');
const pathExists = require('path-exists').sync
const pkgDir = require('pkg-dir').sync;
const npminstall = require('npminstall');
const { isObject, formatPath } = require('@zmz-cli-dev/utils');
const { getDefaultRegistry, getNpmLatestVersion } = require('@zmz-cli-dev/get-npm-info');

class Package {
  constructor(options) {
    if (!options || !isObject(options)) {
      throw new Error('Package类的options不能为空，且必须为对象');
    }
    const { targetPath = '', storeDir = '', packageName = '', packageVersion = '' } = options;
    this.targetPath = targetPath;
    // 缓存pkg的本地路径
    this.storeDir = storeDir;
    this.packageName = packageName;
    this.packageVersion = packageVersion;
    // package的缓存目录前缀
    // this.cacheFilePathPrefix = this.packageName.replace('/', '_');
  }
  // 获取入口文件路径
  getRootFilePath() {
    function _getRootFilePath(targetPath) {
      // 1、获取package.json的路径
      const rootDir = pkgDir(targetPath);
      // 2、读取package.json
      if (rootDir) {
        const pkgFile = require(path.resolve(rootDir, 'package.json'));
        // 3、获取入口文件路径(main/lib)
        if (pkgFile && pkgFile.main) {
          // 4、路径的兼容(macOS/windows)
          return formatPath(path.resolve(rootDir, pkgFile.main));
        }
      }
      return null
    }
    if(this.storeDir){
      return _getRootFilePath(this.cacheFilePath)
    }else{
      return _getRootFilePath(this.targetPath)
    }
  }
  // 获取package最新的版本号
  async prepare(){
    if(this.storeDir && !pathExists(this.storeDir)){ // 缓存目录不存在
      fse.mkdirpSync(this.storeDir); // 创建缓存目录
    }
    if(this.packageVersion === 'latest'){
      this.packageVersion = await getNpmLatestVersion(this.packageName)
    }
  }
  // 获取缓存路径
  get cacheFilePath(){
    // return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`)
    return path.resolve(this.storeDir, this.packageName)
  }
  // 判断pkg是否存在
  async exists() {
    if(this.storeDir){
      await this.prepare()
      console.log(this.cacheFilePath, this.packageVersion)
      return pathExists(this.cacheFilePath)
    }else{
      return pathExists(this.targetPath);
    }
  }
  // 安装Package
  async install(){
    await this.prepare()
    const pkgInfo = {
      root: this.targetPath, // 安装路径
      storeDir: this.storeDir, // 缓存路径
      registry: getDefaultRegistry(), // npm源(默认淘宝源 )
      pkgs: [
        { // 要安装的包
          name: this.packageName,
          version: this.packageVersion
        }
      ]
    }
    return npminstall(pkgInfo)
  }
  // 更新
  async update(){
    // 1、获取最新的版本号
    const latestVersion = await getNpmLatestVersion(this.packageName)
    // console.log('latestVersion', latestVersion)
    // console.log('packageVersion', this.packageVersion)
    // 2、如果版本号有变化，则重新安装
    if(latestVersion && latestVersion !== this.packageVersion){
      this.packageVersion = latestVersion
      await this.install()
    }else{
      console.log('\n已经是最新版本,无需更新')
    }
  }
}

module.exports = Package;

